<?php

eval( ' function xoops_module_uninstall_'.$mydirname.'( $module ) { return links_onuninstall_base( $module , "'.$mydirname.'" ) ; } ' ) ;


if( ! function_exists( 'links_onuninstall_base' ) ) {

	function links_onuninstall_base( $module , $mydirname )
	{
		// transations on module uninstall

		global $ret; // TODO :-D

		require_once realpath(dirname(__FILE__)) . '/functions.php';

		// for Cube 2.1
		if( defined( 'XOOPS_CUBE_LEGACY' ) ) {
			$root =& XCube_Root::getSingleton();
			$root->mDelegateManager->add( 'Legacy.Admin.Event.ModuleUninstall.' . ucfirst($mydirname) . '.Success' , 'links_message_append_onuninstall' ) ;
			$ret = array() ;
		} else {
			if( ! is_array( $ret ) ) $ret = array() ;
		}

		$db =& Database::getInstance() ;
		$mid = $module->getVar('mid') ;

		// TABLES (loading mysql.sql)
		$sql_file_path = dirname(dirname(__FILE__)).'/sql/mysql.sql' ;
		$prefix_mod = $db->prefix() . '_' . $mydirname ;
		if( file_exists( $sql_file_path ) ) {
			$ret[] = "SQL file found at <strong>".htmlspecialchars($sql_file_path)."</strong>.<br  /> Deleting tables...<br />";
			$sql_lines = file( $sql_file_path ) ;
			foreach( $sql_lines as $sql_line ) {
				if( preg_match( '/^CREATE TABLE \`?([a-zA-Z0-9_-]+)\`? /i' , $sql_line , $regs ) ) {
					$sql = 'DROP TABLE '.mysql_real_escape_string($prefix_mod.'_'.$regs[1]);
					if (!$db->query($sql)) {
						$ret[] = '<span style="color:#ff0000;">ERROR: Could not drop table <strong>'.htmlspecialchars($prefix_mod.'_'.$regs[1]).'</strong>.</span><br />';
					} else {
						$ret[] = 'Table <strong>'.htmlspecialchars($prefix_mod.'_'.$regs[1]).'</strong> dropped.<br />';
					}
				}
			}
		}

		// DELETE capture images
		unlink_capture_images($mydirname);

		return true ;
	}

	function links_message_append_onuninstall( &$module_obj , &$log )
	{
		if( is_array( @$GLOBALS['ret'] ) ) {
			foreach( $GLOBALS['ret'] as $message ) {
				$log->add( strip_tags( $message ) ) ;
			}
		}

		// use mLog->addWarning() or mLog->addError() if necessary
	}

	function unlink_capture_images($mydirname)
	{
		global $ret;

		$cache_dir = XOOPS_ROOT_PATH .'/uploads/' . $mydirname . '_capture_cache';

		if (is_dir($cache_dir)) {
			$count = 1;
			$dir = dir($cache_dir);
			$temp_ret = '';
			while(($fileName = $dir->read()) !== FALSE) {
				if ($fileName == '.' || $fileName == '..') continue;
				if ($count == 1) $temp_ret = '[DELETED FILES] ';
				$imagePath = $dir->path . '/' . $fileName;
				if (@unlink($imagePath)) {
					$temp_ret .= htmlspecialchars($fileName, ENT_QUOTES) . ' ';
				}
				$count++;
			}
			if ($count > 1) $temp_ret .= '<br />';
			$ret[] = $temp_ret;
			if (@rmdir($cache_dir)) {
				$ret[] = '[DELETED DIR] '. $cache_dir;
			}
		}
	}
}

